
export function IEVersion() {
    let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    // console.log(userAgent);
    let isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
    let isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
    let isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if(isIE) {
     let reIE = new RegExp("MSIE (\\d+\\.\\d+);");
     let match = reIE.exec(userAgent);
     let fIEVersion = match ? parseFloat(match[1]) : 0;
     if(fIEVersion == 7) {
         return 7;
     } else if(fIEVersion == 8) {
         return 8;
     } else if(fIEVersion == 9) {
         return 9;
     } else if(fIEVersion == 10) {
         return 10;
     } else {
         return 6;//IE版本<=7
     }
    } else if(isEdge) {
     return 'edge';//edge
    } else if(isIE11) {
     return 11; //IE11
    }else{
     return -1;//不是ie浏览器
    }
}

export function downloadFile(fileUrl:string) {
    // 创建一个<a>元素
    const link = document.createElement('a');
    // 设置href属性为文件的URL
    link.href = fileUrl;
    const fileName = fileUrl.split('/').pop() || new Date().getTime().toString();
    // 设置下载的文件名
    link.setAttribute('download', fileName);
    // 将<a>元素添加到body中（Firefox需要）
    document.body.appendChild(link);
    // 模拟点击<a>元素
    link.click();
    // 移除<a>元素
    document.body.removeChild(link);
}
interface DateFormatReplacements {
    [key: string]: number;
    "M+": number;
    "d+": number;
    "h+": number;
    "m+": number;
    "s+": number;
    "q+": number;
    S: number;
}

function _getDate(t: string | Date): Date {
    return typeof t === "string" ? new Date(t) : t;
}

export function format(t: string | Date, n: string): string {
    const date = _getDate(t);
    const replacements: DateFormatReplacements = {
        "M+": date.getMonth() + 1, // 月份从0开始需+1 
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度计算
        S: date.getMilliseconds()
    };

    // 处理年份匹配
    let formatStr = n;
    const yearMatch = /(y+)/.exec(formatStr);
    if (yearMatch) {
        const yearStr = date.getFullYear().toString();
        formatStr = formatStr.replace(yearMatch[0], yearStr.substr(4 - yearMatch[0].length));
    }
    // 遍历替换其他字段
    Object.keys(replacements).forEach((key) => {
        const pattern = new RegExp(`(${key})`);
        const match = pattern.exec(formatStr);
        if (match) {
        const value = replacements[key];
        formatStr = formatStr.replace(
            match[0],
            match[0].length === 1 ? 
            value.toString() : 
            `00${value}`.substr(value.toString().length)
        );
        }
    });

    return formatStr;
}
interface MarkPoint {
    id: string;
    d_id: string[];
    type_name: string;
    count: number;
}

interface NewObjType {
    id: string;
    d_id: string;
    type_name: string;
}
export function updateMarkPoints(newObj: NewObjType, arr: MarkPoint[]): MarkPoint[] {
    // 创建数组浅拷贝
    const newArray = [...arr];
    // 查找相同 ID 的项
    const itemById = newArray.find(item => item.id === newObj.id);

    if (itemById) {
        // 修复原逻辑错误：仅检查当前项的 d_id 是否包含
        const hasExistingDId = itemById.d_id.includes(newObj.d_id);
        
        if (!hasExistingDId) {
        itemById.count += 1;
        itemById.d_id.push(newObj.d_id);
        }
    } else {
        // 不存在相同 ID 则添加新项
        newArray.push({
        id: newObj.id,
        d_id: [newObj.d_id],
        type_name: newObj.type_name,
        count: 1
        });
    }

    // 返回按 count 降序排序的新数组
    return newArray.sort((a, b) => b.count - a.count);
}
interface DataType {
    type_name: string;
    // 可根据实际数据结构扩展其他字段
}
  
interface CategorizedResult {
    typeNames: string[];
    typeCounts: number[];
}

export function categorizeTypes(
    data: DataType[],
    sortByCount: boolean = true
): CategorizedResult {
    const typeMap = new Map<string, number>();

    // 类型安全的统计逻辑
    data.forEach((item: DataType) => {
        const typeName = item.type_name;
        typeMap.set(typeName, (typeMap.get(typeName) || 0) + 1);
    });

    // 转换为可排序数组（显式类型声明）
    const entriesArray: [string, number][] = Array.from(typeMap.entries());

    // 优化排序逻辑
    const sorted = entriesArray.sort((a, b) => {
        return sortByCount 
        ? b[1] - a[1]   // 数量降序
        : a[0].localeCompare(b[0]);  // 名称字母序
    });

    return {
        typeNames: sorted.map(x => x[0]),
        typeCounts: sorted.map(x => x[1])
    };
}
interface DataItem {
    type_name: string;
    count: number;
}
  
interface TypeStatistics {
    typeNames: string[];
    typeCounts: number[];
}
  
export function extractTypeAndCount(dataArray: DataItem[]): TypeStatistics {
    return {
      typeNames: dataArray.map(item => item.type_name),
      typeCounts: dataArray.map(item => item.count)
    };
}
interface DataItem {
    type_name: string;
    // 可根据实际数据结构扩展其他字段
}
  
type TypeCount = {
    type_name: string;
    count: number;
};
  
export function countAndSortByType(data: DataItem[]): TypeCount[] {
    // 1. 使用类型安全的 reduce 统计
    const countMap = data.reduce<Record<string, number>>((acc, item) => {
      const type = item.type_name;
      acc[type] = (acc[type] || 0) + 1;
      return acc;
    }, {});
  
    // 2. 转换为类型安全的数组并排序
    return Object.entries(countMap)
      .map<TypeCount>(([type_name, count]) => ({ type_name, count }))
      .sort((a, b) => b.count - a.count);
}